package bamin.com.bamindaijia.Activity;

import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.TextView;

import com.aiton.administrator.shane_library.shane.app.SysApplication;
import com.aiton.administrator.shane_library.shane.utils.ACache;
import com.aiton.administrator.shane_library.shane.widget.MyProgressDialog;
import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClient;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.location.AMapLocationListener;
import com.amap.api.services.core.AMapException;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.help.Inputtips;
import com.amap.api.services.help.Tip;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import bamin.com.bamindaijia.R;
import bamin.com.bamindaijia.adapter.MySearchAdapter;
import bamin.com.bamindaijia.constant.Constant;
import bamin.com.bamindaijia.model.MyLatLonPoint;
import bamin.com.bamindaijia.model.MyTip;

public class AddComAddressActivity extends ZjbBaseActivity implements View.OnClickListener {

    private View mSite_head;
    private EditText mEditText_where;
    private TextView mTextView_city;
    private ListView mListView_search;
    private List<Tip> listSearch = new ArrayList<>();
    private Inputtips mInputtips;
    private String mCityCode;
    private String mCity;
    private String mChosseType;
    //声明定位回调监听器
    public AMapLocationListener mLocationListener = new AMapLocationListener() {


        @Override
        public void onLocationChanged(AMapLocation amapLocation) {
            if (amapLocation != null) {
                if (amapLocation.getErrorCode() == 0) {
                    //定位成功回调信息，设置相关消息
                    double latitude = amapLocation.getLatitude();//获取纬度
                    double longitude = amapLocation.getLongitude();//获取经度
                    if (mProgressDialog != null && mProgressDialog.isShowing()) {
                        mProgressDialog.dismiss();//定位后取消progressDialog
                        mProgressDialog = null;
                    }


                    mCityCode = amapLocation.getCityCode();
                    mCity = amapLocation.getCity();
                    mTextView_city.setText(mCity);


                } else {
                    //显示错误信息ErrCode是错误码，errInfo是错误信息，详见错误码表。
                    Log.e("AmapError", "location Error, ErrCode:"
                            + amapLocation.getErrorCode() + ", errInfo:"
                            + amapLocation.getErrorInfo());
                }
            }
        }

    };
    private MyProgressDialog mProgressDialog;
    private AMapLocationClient mLocationClient;
    private AMapLocationClientOption mLocationOption;
    private MySearchAdapter mAdapterSearch;
    @Override
    protected void onDestroy() {
        super.onDestroy();
        mLocationClient.stopLocation();
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_add_com_address);
        init();
        initMap();
    }
    private void initMap(){
        //初始化定位
        mLocationClient = new AMapLocationClient(getApplicationContext());
        //设置定位回调监听
        mLocationClient.setLocationListener(mLocationListener);
        //初始化定位参数
        mLocationOption = new AMapLocationClientOption();
        //设置定位模式为高精度模式，Battery_Saving为低功耗模式，Device_Sensors是仅设备模式
        mLocationOption.setLocationMode(AMapLocationClientOption.AMapLocationMode.Hight_Accuracy);
        //设置是否返回地址信息（默认返回地址信息）
        mLocationOption.setNeedAddress(true);
        //设置是否只定位一次,默认为false
        mLocationOption.setOnceLocation(true);
        //设置是否强制刷新WIFI，默认为强制刷新
        mLocationOption.setWifiActiveScan(true);
        //设置是否允许模拟位置,默认为false，不允许模拟位置
        mLocationOption.setMockEnable(false);
        //设置定位间隔,单位毫秒,默认为2000ms
        mLocationOption.setInterval(2000);
        //给定位客户端对象设置定位参数
        mLocationClient.setLocationOption(mLocationOption);
        //启动定位
        mLocationClient.startLocation();
    }
    @Override
    protected void initData() {

    }

    @Override
    protected void initViews() {
        setProgressDialog("正在定位……");
        mAdapterSearch = new MySearchAdapter(this, listSearch);
        mListView_search.setAdapter(mAdapterSearch);
    }

    @Override
    protected void setListeners() {
        mEditText_where.addTextChangedListener(new MyTextWatcher());
        mInputtips = new Inputtips(this, new Inputtips.InputtipsListener() {
            @Override
            public void onGetInputtips(List<Tip> list, int i) {
                listSearch.addAll(list);

                Iterator<Tip> iterator = listSearch.iterator();
                while(iterator.hasNext()){
                    Tip tip = iterator.next();
                    if (TextUtils.isEmpty(tip.getAdcode()) || TextUtils.isEmpty(tip.getAddress()) || TextUtils.isEmpty(tip.getDistrict()) ) {
                        Log.e("ChosseSite", "onGetInputtips: --->>" + tip.getName());

                        iterator.remove();
                    }

                }
                mAdapterSearch.notifyDataSetChanged();
                for (int j = 0; j < list.size(); j++) {
                    Log.e("onGetInputtips", "提示返回结果" + list.get(j).getName());
                }
            }
        });

        findViewById(R.id.textView_cancle).setOnClickListener(this);
        mListView_search.setOnItemClickListener(new MySearchOnItemClickListener());
    }
    class MySearchOnItemClickListener implements AdapterView.OnItemClickListener {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            Tip tip = listSearch.get(position);
            Log.e("tip","Adcode:"+tip.getAdcode());
            Log.e("tip","Address:"+tip.getAddress());
            Log.e("tip","District:"+tip.getDistrict());
            Log.e("tip","PoiID:"+tip.getPoiID());
            Log.e("tip","Name:"+tip.getName());
            Log.e("tip","Postion:"+tip.getPoint());

            MyTip myTip = new MyTip();
            LatLonPoint point = tip.getPoint();
            //将高德地图中的Tip数据传到自己建立的MyTip类中
            MyLatLonPoint myLatLonPoint = new MyLatLonPoint(point.getLatitude(),point.getLongitude());
            myTip.setAdcode(tip.getAdcode());
            myTip.setAddress(tip.getAddress());
            myTip.setDistrict(tip.getDistrict());
            myTip.setID(tip.getPoiID());
            myTip.setName(tip.getName());
            myTip.setPostion(myLatLonPoint);

            //家的地址
            if (Constant.INTENT_KEY.COMMONLY_ADDRESS_HOME.equals(mChosseType)) {

                ACache aCache = ACache.get(AddComAddressActivity.this);
                aCache.put(Constant.ACACHE.TIP_HOME,  myTip);
                MyTip asObject = (MyTip) aCache.getAsObject(Constant.ACACHE.TIP_HOME);
                Log.e("myTip","getName:"+asObject.getName());



            //公司地址
            } else if (Constant.INTENT_KEY.COMMONLY_ADDRESS_COMPANY.equals(mChosseType)) {

                ACache aCache = ACache.get(AddComAddressActivity.this);
                aCache.put(Constant.ACACHE.TIP_COMPANY,  myTip);
                Log.e("myTip","getName:"+myTip.getName());
            }

            finishTo();
        }
    }
    @Override
    protected void initSP() {

    }

    @Override
    protected void initIntent() {
        Intent intent = getIntent();
        mChosseType = intent.getStringExtra(Constant.INTENT_KEY.CHOSSE_TYPE);
    }

    @Override
    protected void findID() {
        mEditText_where = (EditText) findViewById(R.id.editText_where);
        mTextView_city = (TextView) findViewById(R.id.textView_city);
        mListView_search = (ListView) findViewById(R.id.listView_search);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.textView_cancle:
                finishTo();
                break;
            case R.id.textView_city:
                Intent intent = new Intent(this, CityPickerActivity.class);
                startActivityForResultTo(intent, Constant.REQUEST_RESULT_CODE.CHOOSE_CITY);
                break;
        }
    }
    class MyTextWatcher implements TextWatcher {

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            Log.e("onTextChanged", "" + s);
            try {
                listSearch.clear();
                mAdapterSearch.notifyDataSetChanged();
                if (!"".equals(s)) {
                    mInputtips.requestInputtips(s + "", "" + mCityCode);
                }
            } catch (AMapException e) {
                e.printStackTrace();
            }
        }

        @Override
        public void afterTextChanged(Editable s) {

        }
    }

    private void setProgressDialog(String text) {
        if (mProgressDialog == null) {
            mProgressDialog = new MyProgressDialog(this,text);
            mProgressDialog.setCancelable(false);
            mProgressDialog.show();
            mProgressDialog.setOnKeyListener(new DialogInterface.OnKeyListener() {
                @Override
                public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
                    if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
                        mProgressDialog.dismiss();
                        SysApplication.getInstance().exit();
                    }
                    return false;
                }
            });
        } else {

        }
    }
}
